<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Dao;

use App\Exception\CustomException;
use App\Kernel\Traits\DaoTrait;
use App\Model\User;
use App\Model\UserBill;

use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Db;

/**
 * 用户 Dao
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Dao
 */
class UserDao extends Dao
{
    use DaoTrait;
    /**
     * @var string
     */
    const INTEGRAL = 'integral';

    /**
     * @var string
     */
    const MONEY = 'money';

    /**
     * 用户角色-会员
     *
     * @var int
     */
    const USER_MEMBER = 1;

    /**
     * 用户角色-渠道商
     *
     * @var int
     */
    const USER_CHANNEL_BUSINESS = 2;

    /**
     * 用户角色-商家
     *
     * @var int
     */
    const USER_BUSINESS = 3;

    /**
     * 通过区域取渠道商
     * @param array $map
     * @return mixed
     */
    public function areaAgent(array $map)
    {
        return User::query()
            ->where(function($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->paginate(10);
    }

    /**
     * 总后台会员列表
     * @param array $map
     * @return mixed
     */
    public function lowerLevel(array $map)
    {
        return User::query()
            ->where(function($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->select('id','created_at','name','phone','district','identity_code','parent_id','group_id','integral')
            ->paginate(10);
    }

    /**
     * 总后台会员列表
     *
     * @return mixed
     */
    public function PageList()
    {
        return User::query()
            ->where('status',1)
            ->select('id','created_at','name','phone','district','identity_code','parent_id','group_id','integral')
            ->paginate(10);
    }

    /**
     * 通过上级ID获取用户
     *
     * @param int $id ID
     * @param bool $abnormal 是否抛异常
     * @return mixed
     */
    public function parentFirst(int $id, bool $abnormal = true)
    {
        $result = User::query()->where('parent_id', $id)->first();

        if (!$result && $abnormal === true) {
            $this->error('USER.NOT_FOUND');
        }

        return $result;
    }

    /**
     * 统计用户分享的会员为他带来积分收益的明细列表
     *
     * @param array $map
     * @param bool $abnormal 是否抛异常
     * @return mixed
     */
    public function get(array $map, bool $abnormal = true)
    {
        $result = User::query()
            ->where(function($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->select('id','avatar','name','phone')
            ->orderByRaw("created_at desc,id desc")
            ->paginate(10);

        if (!$result && $abnormal === true) {
            $this->error('USER.NOT_FOUND');
        }

        return $result;
    }

    /**
     * 通过ID获取用户
     *
     * @param int $id ID
     * @param bool $abnormal 是否抛异常
     * @return mixed
     */
    public function first(int $id, bool $abnormal = true)
    {
        $result = User::query()->where('id', $id)->first();

        if (!$result && $abnormal === true) {
            $this->error('USER.NOT_FOUND');
        }

        return $result;
    }

    /**
     * 通过手机号码登陆或创建用户
     *
     * @param string $phone 手机号码
     * @param string $login_pwd 登录密码
     * @param int $parent_id 上级ID
     * @return mixed
     */
    public function loginByPhoneOrCreate(string $phone, $login_pwd, int $parent_id)
    {
        return User::query()->firstOrCreate(['phone' => $phone], [
            'parent_id' => $parent_id,
            'name' => $phone,
            'login_pwd' => $login_pwd,
            'status' => true,
            'group_id' => 1
        ]);
    }

    /**
     * 通过手机号码登陆或创建用户
     *
     * @param string $phone 手机号码
     * @param string $login_pwd 登录密码
     * @param int $parent_id 上级ID
     * @return mixed
     */
    public function loginByCreate(string $phone, $login_pwd, int $parent_id)
    {
        return User::query()->Create([
            'phone' => $phone,
            'parent_id' => $parent_id,
            'name' => $phone,
            'login_pwd' => $login_pwd,
            'status' => true,
            'group_id' => 1
        ]);
    }

    /**
     * 通过手机号码登陆或创建用户
     *
     * @param string $phone 手机号码
     * @return mixed
     */
    public function loginByPhone(string $phone)
    {
        return User::query()->where(['phone' => $phone])->first();
    }

    /**
     * 修改数据
     *
     * @param array $data
     * @return int
     */
    public function update(array $data)
    {
        return User::query()->where('id', uid())->update($data);
    }

    /**
     * 通过邀请码获得上级
     *
     * @param string $identity_code 邀请码
     * @param bool $abnormal 是否抛异常
     * @return mixed
     */
    public function getParentByIdentityCode(string $identity_code, bool $abnormal = true)
    {
        $result = User::query()->where('identity_code', $identity_code)->select('id')->first();

        if (!$result && $abnormal === true) {
            $this->error('USER.INVITATION_CODE_NOT_FOUND');
        }

        return $result;
    }

    /**
     * 通过手机号查询数据
     * @param string $phone
     * @param array $select
     * @return mixed
     */
    public function getPhoneByUser( string $phone, array $select)
    {
        $result = User::query()->where('phone', $phone)->select($select)->first();

        if( !$result ) {
            $this->error('USER.PHONE_FAIL');
        }

        return $result;
    }

    /**
     * 通过手机号查询数据
     * @param string $phone
     * @param array $select
     * @return mixed
     */
    public function getPhoneShare( string $phone, array $select)
    {
        return User::query()->where('phone', $phone)->select($select)->first();
    }

    /**
     * 找回密码
     *
     * @param array $data
     * @param array $where
     * @return int
     */
    public function retrieve( array $data, array $where)
    {
        return User::query()->where($where)->update($data);
    }

    /**
     * 自增
     *
     * @param int $user_id
     * @param string $num
     * @param string $column
     * @return int
     */
    public function increment(int $user_id, string $num, string $column)
    {
        return User::query()->where('id', $user_id)->increment($column, $num);
    }

    /**
     * 自减
     *
     * @param int $user_id
     * @param int $num
     * @param string $column
     * @return int
     */
    public function decrement(int $user_id, int $num, string $column)
    {
        return User::query()->where('id', $user_id)->decrement($column, $num);
    }

    /**
     * 统计会员分享数量
     *
     * @param array $map
     * @return mixed
     */
    public function count(array $map = [])
    {
        return User::query()
            ->where(function($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->count();
    }

    /**
     * 统计用户分享的会员为他带来积分收益的明细列表
     *
     * @param array $map
     * @param string $sort
     * @return mixed
     */
    public function getIntegralByMember(array $map , $sort)
    {
        return User::query()
            ->with('userIntegral:id,user_id,num,order_no')
            ->where(function($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->select('id','avatar','name','phone')
            ->orderByRaw($sort)
            ->paginate(10);
    }

    /**
     * 通过邀请码获取用户
     *
     * @param string $identity_code
     * @param string $field
     * @param bool $abnormal
     * @return mixed
     */
    public function getUserByIdentityCode(string $identity_code, $field = '*',$group,bool $abnormal = true )
    {
        $result = User::query()
            ->where('identity_code', $identity_code)
            ->where('group_id', $group)
            ->select($field)->first();

        if (!$result && $abnormal === true) {
            $this->error('USER.NOT_USER_CHANNEL_BUSINESS');
        }

        return $result;
    }

    /**
     * 通过id数组获取信息
     * @param array $ids
     * @param array $select
     * @return mixed
     */
    public function getUserByIds(array $ids, array $select)
    {
        return User::query()
            ->whereIn('id', $ids)
            ->select($select)
            ->get()->groupBy('id');
    }

    public function getUsersByIdsNotGroup(array $ids, array $select)
    {
        return User::query()
            ->whereIn('id', $ids)
            ->select($select)
            ->get();
    }

    /**
     * 获取用户通过map
     * @param array $map
     * @param string|null $sort
     * @param array|null $select
     * @param int|null $paginate
     * @return mixed
     */
    public function getUsersByMap(array $map = [], string $sort = null,array $select = null, int $paginate = null)
    {
        $model = self::makeModel();

        if (isset($map['between_field'])) {
            foreach ($map['between_field'] as $k => $value) {
                $model = $model->whereBetween($k, $value);
            }
            unset($map['between_field']);
        }

        // 或
        if (isset($map['or_field'])) {
            $model = $model->where(function (Builder $query) use($map) {
                foreach ($map['or_field'] as $field => $item) {
                    // 普通查询
                    if (!is_array($item)) {
                        $query->orWhere($field, $item);
                        continue;
                    }
                    // 其它方式
                    switch (strtolower($item[0])) {
                        case 'in':
                            $query->orWhereIn($field, $item[1]);
                            break;

                        default:
                            $query->orWhere($field, $item[0], $item[1]);
                    }
                }
            });

            unset($map['or_field']);
        }

        if (!empty($map)) {
            $model = $model->where(function ($query) use ($map) {
                return queryWhere($query, $map);
            });
        }
        if (null !== $sort) {
            $model = $model->orderByRaw($sort);
        }

        if (null !== $select) {
            $model = $model->select($select);
        }

        return $paginate > 0 ? $model->paginate($paginate) : $model->get();
    }


    /**
     * Get model.
     *
     * @return string
     */
    public function model(): string
    {
        return User::class;
    }

    /**
     * 获取下级用户数量通过ID数组
     * @param array $ids
     * @return array
     */
    public function getLowerUserCountByIds(array $ids)
    {
        return User::query()
            ->whereIn('parent_id', $ids)
            ->selectRaw('parent_id, count(parent_id) as lower_count')
            ->groupBy("parent_id")
            ->get()
            ->pluck('lower_count', 'parent_id')
            ->toArray();
    }

    /**
     * 通过ID获得用户分组
     * @param array $ids
     * @param string $select_raw
     * @param $group_by
     * @return mixed
     */
    public function getSelectRawByIds(array $ids, string $select_raw, $group_by)
    {
        return User::query()
            ->whereIn('parent_id', $ids)
            ->selectRaw($select_raw)
            ->groupBy($group_by)
            ->get();
    }


    public function updateUserById(int $id, array $data)
    {
        return User::query()->where('id', $id)->update($data);
    }

}